<template>
  <el-card style="height: 70px; margin-bottom: 10px">
    <el-form class="form" :inline="true">
      <el-form-item label="用户名:">
        <el-input
          placeholder="请输入搜索的用户名"
          clearable
          v-model="username"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="search">搜索</el-button>
        <el-button plain @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card>
    <el-button type="primary" @click="addUser">添加</el-button>
    <el-button
      type="danger"
      @click="batchDelete"
      :disabled="selectIdArr.length > 0 ? false : true"
    >
      批量删除
    </el-button>
    <el-table
      border
      style="margin: 10px 0px"
      :data="tableData"
      @selection-change="selectChange"
    >
      <el-table-column type="selection"></el-table-column>
      <el-table-column type="index" label="#" width="80px"></el-table-column>
      <el-table-column label="ID" prop="id"></el-table-column>
      <el-table-column
        label="用户名字"
        prop="username"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="用户名称"
        prop="name"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="用户角色"
        prop="roleName"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="创建时间"
        prop="createTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="更新时间"
        prop="updateTime"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="操作" width="320px" align="center">
        <template #="{ row }">
          <el-button type="primary" icon="User" @click="setRole(row)">
            分配角色
          </el-button>
          <el-button type="primary" icon="Edit" @click="editUser(row)">
            编辑
          </el-button>
          <el-button type="primary" icon="Delete" @click="deleteUser(row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="limit"
      :page-sizes="[10, 20, 30, 40]"
      :background="true"
      layout="prev, pager, next, jumper,->,sizes, total,"
      :total="total"
      @current-change="getDataList"
      @size-change="handler"
    />
    <!-- 添加和编辑 -->
    <el-drawer v-model="drawer">
      <template #header>
        <h4>{{ title }}</h4>
      </template>
      <template #default>
        <el-form :model="userParams" ref="form" :rules="relus">
          <el-form-item label="用户姓名" prop="username">
            <el-input
              placeholder="请输入用户名"
              v-model="userParams.username"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户昵称" prop="name">
            <el-input
              placeholder="请输入用户昵称"
              v-model="userParams.name"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="用户密码"
            v-if="title != '编辑用户'"
            prop="password"
          >
            <el-input
              placeholder="请输入用户密码"
              v-model="userParams.password"
            ></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawer = false">取消</el-button>
          <el-button type="primary" @click="confirmClick">确定</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 分配角色 -->
    <el-drawer v-model="drawerRole">
      <template #header>
        <h4>分配角色</h4>
      </template>
      <template #default>
        <el-form>
          <el-form-item label="用户姓名">
            <el-input disabled v-model="userParams.username"></el-input>
          </el-form-item>
          <el-form-item label="角色列表">
            <el-checkbox
              v-model="checkAll"
              :indeterminate="isIndeterminate"
              @change="handleCheckAllChange"
            >
              全选
            </el-checkbox>

            <el-checkbox-group
              v-model="userRole"
              @change="handleCheckedUsersChange"
            >
              <el-checkbox
                v-for="(role, index) in allRole"
                :key="index"
                :label="role"
              >
                {{ role.roleName }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawerRole = false">取消</el-button>
          <el-button type="primary" @click="confirmRole">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </el-card>
</template>
<script setup lang="ts">
import { reactive, ref, nextTick } from 'vue'
import {
  reqUserInfo,
  reqAddOrUpdateUser,
  reqAllRole,
  reqSetUserRole,
  reqRemoveUser,
  reqSelectUser,
} from '@/api/acl/user'
import type {
  UserResponseData,
  Records,
  User,
  AllRole,
  AllRoleResponseData,
} from '@/api/acl/user/type'
import { ElMessage } from 'element-plus'
const pageNo = ref<number>(1)
const limit = ref<number>(10)
const total = ref(0)
const tableData = ref<Records>([])
const username = ref<string>('')
const drawer = ref<boolean>(false)
const drawerRole = ref<boolean>(false)
const title = ref<string>('')
const form = ref()
const checkAll = ref(false)
const userRole = ref<AllRole>([])
const allRole = ref<AllRole>([])
const isIndeterminate = ref(false)
const selectIdArr = ref<User[]>([])
const userParams = reactive<User>({
  username: '',
  name: '',
  password: '',
})
import useLayOutSettingStore from '@/store/modules/setting'
let settingStore = useLayOutSettingStore()

const validatorName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 5) {
    callBack()
  } else {
    callBack(new Error('用户昵称至少五位'))
  }
}
const relus = {
  username: [
    { required: true, message: '用户名称不能为空', trigger: 'blur' },
    { required: true, min: 5, message: '用户名称至少5位', trigger: 'blur' },
  ],
  name: [{ required: true, trigger: 'blur', validator: validatorName }],
  password: [
    { required: true, message: '用户名称不能为空', trigger: 'blur' },
    { required: true, min: 6, message: '用户密码至少6位', trigger: 'blur' },
  ],
}
// 刷新
const search = () => {
  getDataList()
  // username.value = ''
}
// 重置
const reset = () => {
  settingStore.refsh = !settingStore.refsh
}
// 获取列表
const getDataList = async (pager = 1) => {
  pageNo.value = pager
  const res: UserResponseData = await reqUserInfo(
    pageNo.value,
    limit.value,
    username.value,
  )
  if (res.code == 200) {
    tableData.value = res.data.records
    total.value = res.data.total
  }
}
getDataList()
const handler = () => {
  getDataList()
}

// 添加用户
const addUser = async () => {
  drawer.value = true
  title.value = '添加用户'
  // 清空数数据
  Object.assign(userParams, {
    username: '',
    name: '',
    password: '',
    id: '',
  })
  // 清空校验
  nextTick(() => {
    form.value.clearValidate('name')
    form.value.clearValidate('username')
    form.value.clearValidate('password')
  })
}
const selectChange = (value: any) => {
  selectIdArr.value = value
}
// 批量删除
const batchDelete = async () => {
  let idList: any = selectIdArr.value.map((item) => item.id)
  const res: any = await reqSelectUser(idList)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '批量删除成功',
    })
    getDataList(tableData.value.length > 1 ? pageNo.value : pageNo.value - 1)
  }
}
// 编辑用户
const editUser = async (row: any) => {
  drawer.value = true
  title.value = '编辑用户'
  // 获取数据
  Object.assign(userParams, row)
  // 清空校验
  nextTick(() => {
    form.value.clearValidate('name')
    form.value.clearValidate('username')
    form.value.clearValidate('password')
  })
}
// 确定按钮
const confirmClick = async () => {
  // 表单校验
  await form.value.validate()

  const res: any = await reqAddOrUpdateUser(userParams)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '添加成功',
    })
    drawer.value = false
    // getDataList(userParams.id ? pageNo.value : 1) // 和下边的刷新浏览器冲突，可以不要
    // 浏览器自动刷新一次，确保修改当前登录账户，获取不到当前登录账号的信息
    window.location.reload()
  } else {
    ElMessage({
      type: 'error',
      message: res.data,
    })
  }
}
// 分配角色
const setRole = async (row: User) => {
  drawerRole.value = true
  Object.assign(userParams, row)

  let res: AllRoleResponseData = await reqAllRole(userParams.id as number)

  if (res.code == 200) {
    allRole.value = res.data.allRolesList
    userRole.value = res.data.assignRoles
    // 全选框按钮的样式
    if (userRole.value.length > 0) {
      let checkedCount = userRole.value.length
      checkAll.value = checkedCount === allRole.value.length
      isIndeterminate.value =
        checkedCount > 0 && checkedCount < allRole.value.length
    } else {
      isIndeterminate.value = false
    }
  }
}
const handleCheckAllChange = (val: boolean) => {
  userRole.value = val ? allRole.value : []
  isIndeterminate.value = false
}
const handleCheckedUsersChange = (value: string[]) => {
  const checkedCount = value.length
  checkAll.value = checkedCount === allRole.value.length
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < allRole.value.length
}
// 角色的确定按钮
const confirmRole = async () => {
  let params = {
    userId: userParams.id as number,
    roleIdList: userRole.value.map((item) => item.id as number),
  }
  const res = await reqSetUserRole(params)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '分配成功',
    })
    drawerRole.value = false
    getDataList(pageNo.value)
  } else {
    ElMessage({
      type: 'error',
      message: res.data,
    })
  }
}

// 删除用户
const deleteUser = async (userId: number) => {
  const res = await reqRemoveUser(userId)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getDataList(tableData.value.length > 1 ? pageNo.value : pageNo.value - 1)
  }
}
</script>
<style scoped lang="scss">
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
